import React, { useState, useEffect } from 'react';
import store from '../../store'
import { setLists } from '../../store/actionCreater'
import './statepage.css'
const StatePage: React.FC = (props: any) => {
  const [count, setCount] = useState(0);
  const [list,setList] = useState<Array<{value: string}>>([])
  // redux-thunk
  // useEffect(() => {
  //   let action = setLists()
  //   store.dispatch(action)
  //  },[]);

    // redux-saga
  useEffect(() => {
    let action = {
      type: 'getList-saga',
      payload: {}
    }
    store.dispatch(action)
   },[]);
  useEffect(() => {
    //订阅改变
    store.subscribe(()=>{
      console.log(store.getState().list)
     setList(store.getState().list)
    })
   },[list]);//第二个参数为监听什么发生变化才会执行
  function addlist (value:string) {
    store.dispatch({
      type: 'addList',
      value: {value: '新添加的数据'+ Math.random().toFixed(2) }
    })
  }
  function clear() {
    store.dispatch({
      type: 'clearListdefault-saga',
    })
  }
  function getList () {
    //sgag请求数据
    let action = {
      type: 'getList-saga',
      payload: {}
    }
    store.dispatch(action)
  }
  return (
   <div>
     <p>state</p>
     <button onClick={()=>getList()}>请求saga数据</button>
     <button onClick={()=>addlist('q')}>添加数据</button>
     <button onClick={()=>clear()}>清空列表</button>
     <div className='list-content'>
        {
            list.map((item,index)=>{
              return <p key={index}>{index+1}.{item.value}</p>
            })
          }
     </div>
     
   </div>
  );
};

export default StatePage